﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Reflection;

namespace FullRefreshService.Logging
{
    public class FileLogger : ILogger
    {
        private static readonly object LockObject = new object();

        #region ILogger Members

        public void WriteLine(string message)
        {
            DirectoryInfo LogDir = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "Logs"));
            if (!Directory.Exists(LogDir.FullName))
                Directory.CreateDirectory(LogDir.FullName);

            FileInfo logFile = new FileInfo(Path.Combine(LogDir.FullName, State.RunStartTime.ToString("yyyyMMddHHmm") + ".txt"));
            WriteLineBase(logFile, message);
        }

        #endregion

        public static void WriteLineBase(FileInfo file, string line)
        {
            // Perform logging in a separate thread so as not to impact service call duration
            ThreadPool.QueueUserWorkItem(_ =>
            {
                lock (LockObject)
                {
                    StreamWriter logWriter;

                    try
                    {
                        if (File.Exists(file.FullName))
                        {
                            logWriter = new StreamWriter(new FileStream(file.FullName, FileMode.Append, FileAccess.Write, FileShare.None));
                        }
                        else
                        {
                            logWriter = new StreamWriter(new FileStream(file.FullName, FileMode.CreateNew, FileAccess.Write, FileShare.None));
                        }
                    }
                    catch
                    {
                        throw new ApplicationException("Log file locked");
                    }

                    logWriter.WriteLine(line);
                    logWriter.Flush();
                    logWriter.Close();
                }
            });
        }

    }
}
